import requests
from ..utils.storage import get_auth_info
from ..utils.config import config

class APIClient:
    """API请求客户端，自动加载认证信息"""
    
    def __init__(self):
        # 从配置中获取API设置
        api_config = config.get('api', {})
        auth_config = config.get('auth', {})
        
        self.base_url = api_config.get('base_url', 'https://api.example.com')
        self.timeout = api_config.get('timeout', 30)
        self.token_header = auth_config.get('token_header', 'Authorization')
        self.token_prefix = auth_config.get('token_prefix', 'Bearer')
        
        self.session = requests.Session()
    
    def _prepare_request(self, **kwargs):
        """准备请求，添加认证信息"""
        # 从auth.json获取认证信息
        auth_info = get_auth_info()
        
        # 设置headers（如果没有提供）
        if 'headers' not in kwargs:
            kwargs['headers'] = {}
        
        # 添加token到请求头
        if auth_info.get('token'):
            kwargs['headers'][self.token_header] = f"{self.token_prefix} {auth_info['token']}"
        
        # 添加cookies
        if auth_info.get('cookies'):
            # 将cookies添加到session
            for key, value in auth_info['cookies'].items():
                self.session.cookies.set(key, value)
        
        # 设置超时
        if 'timeout' not in kwargs:
            kwargs['timeout'] = self.timeout
        
        return kwargs
    
    def get(self, endpoint, **kwargs):
        """发送GET请求"""
        kwargs = self._prepare_request(**kwargs)
        url = f"{self.base_url}{endpoint}"
        return self.session.get(url, **kwargs)
    
    def post(self, endpoint, data=None, json=None, **kwargs):
        """发送POST请求"""
        kwargs = self._prepare_request(**kwargs)
        url = f"{self.base_url}{endpoint}"
        return self.session.post(url, data=data, json=json, **kwargs)
    
    def put(self, endpoint, data=None, **kwargs):
        """发送PUT请求"""
        kwargs = self._prepare_request(**kwargs)
        url = f"{self.base_url}{endpoint}"
        return self.session.put(url, data=data, **kwargs)
    
    def delete(self, endpoint, **kwargs):
        """发送DELETE请求"""
        kwargs = self._prepare_request(**kwargs)
        url = f"{self.base_url}{endpoint}"
        return self.session.delete(url, **kwargs)

# 创建一个默认的API客户端实例
api_client = APIClient() 